package com.jincp.common.okhttp3.progress;

import java.io.IOException;
import java.util.Observable;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by lidongyang on 2016/5/11.
 */
public class ProgressInterceptor extends Observable implements Interceptor {

    private volatile static ProgressInterceptor instance;

    public static ProgressInterceptor getInstance(){
        if (instance == null) {
            synchronized (ProgressInterceptor.class) {
                if (instance == null) {
                    instance = new ProgressInterceptor();
                }
            }
        }
        return instance;
    }

    private final ProgressBean progressBean;

    private ProgressInterceptor() {
        this.progressBean = new ProgressBean();
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        final String url = request.url().toString();
        return response.newBuilder().body(new ProgressResponseBody(response.body(), new ProgressListener() {

            @Override
            public void update(long currentLength, long totalLength, boolean done) {
                progressBean.target = url;
                progressBean.currentLength = currentLength;
                progressBean.totalLength = totalLength;
                progressBean.done = done;
                setChanged();
                notifyObservers(progressBean);
            }
        })).build();
    }

    public static class ProgressBean {
        public Object target;
        public long currentLength;
        public long totalLength;
        public boolean done;
    }
}
